package com.booktrading.config;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Controller
public class GlobalExceptionHandler implements ErrorController {

    @ExceptionHandler(AccessDeniedException.class)
    public ModelAndView handleAccessDeniedException(AccessDeniedException ex, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("error", "访问被拒绝：" + ex.getMessage());
        mav.addObject("url", request.getRequestURL());
        mav.setViewName("error/403");
        return mav;
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<Map<String, Object>> handleMaxSizeException(MaxUploadSizeExceededException ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "文件大小超过限制");
        return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(response);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleNotFound(NoHandlerFoundException ex, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("error", "请求的页面不存在");
        mav.addObject("url", request.getRequestURL());
        mav.setViewName("error/404");
        return mav;
    }

    @RequestMapping("/error")
    public ModelAndView handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        ModelAndView mav = new ModelAndView();
        mav.addObject("url", request.getRequestURL());
        
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                mav.setViewName("error/404");
                mav.addObject("error", "请求的页面不存在");
            } else if (statusCode == HttpStatus.FORBIDDEN.value()) {
                mav.setViewName("error/403");
                mav.addObject("error", "访问被拒绝");
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                mav.setViewName("error/500");
                mav.addObject("error", "服务器内部错误");
            } else {
                mav.setViewName("error/500");
                mav.addObject("error", "发生未知错误");
            }
        } else {
            mav.setViewName("error/500");
            mav.addObject("error", "发生未知错误");
        }
        
        return mav;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleDefaultException(Exception ex, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("error", ex.getMessage());
        mav.addObject("url", request.getRequestURL());
        mav.setViewName("error/500");
        return mav;
    }
} 